import { syncSetTimeout, sendMessage, getMessage } from "../../global/tools.js";
import { nextContect } from "./localTools.js";
import AiccyunHandler from "./AiccyunHandler.js";
import TextLinkage from "./TextLinkage.js";
import Auto from "./Auto.js";
import AjaxHook from "./AjaxHook.js";
import TaskQueue from "./TaskQueue.js";
import CheckPayment from "./CheckPayment.js";

export default class WebController {
    static count = 0;
    constructor(permission) {
        WebController.count++;
        if (WebController.count >= 2) {
            alert("aiccyunPlugin: \nError: WebController.count >= 2，即将刷新页面。");
            location.reload(true);
        } 
        console.warn("[aiccyunPlugin]", "WebController.js is running.");
        this.permission = permission;
        this.document = () => document;
        this.config = {};
        this.init();
    }
    init() {
        {
            {
                localforage.getItem("collectionPlugin").then(config => {
                    if (config) {
                        this.config = config;
                    } else {
                        alert("[conllectionPlugin]Error: anmi -> modules -> WebController.js -> init() -> 'config' is null.");
                        this.config = {};
                    }
                });
            }
            // 页面关闭前保存数据到localforage
            window.onbeforeunload = async() => {
                localforage.setItem("collectionPlugin", this.config);
            };
        }
        // 载入模块
        {
            let modulesConfig = {
                "aiccyunHandler": AiccyunHandler,
                "textLinkage": TextLinkage,
                "auto": Auto,
                "ajaxHook": AjaxHook,
                "taskQueue": TaskQueue,
                "checkPayment": CheckPayment
            };
            
            Object.keys(modulesConfig).forEach(item => {
                // 用户组不是admin并且permission.config.assignment中没有item这个模块，则不载入
                if ((this.permission.config.userPermission !== "admin") && (!this.permission?.config?.assignment?.includes(item))) {
                    return;
                }
                if (modulesConfig[item]) {
                    this[item] = new modulesConfig[item](this);
                }
            });
        }
    }
}